﻿using System.Collections.Generic;
using System.Net;
using System.Text;
using System.Web;
using Kugar.Core.ExtMethod;
using Kugar.UI.Web.AdminLTE.Enums;
using Kugar.UI.Web.AdminLTE.Helpers;
using Kugar.UI.Web.AdminLTE.PageControls.Helpers.ButtonExtMethod;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Kugar.UI.Web.AdminLTE.PageControls
{
    public class ButtonConfigBase:AdminLTEElementBase, ICommandElement
    {
        internal ButtonTypeEnum _type = ButtonTypeEnum.button;

        public ButtonConfigBase(ViewContext viewContext) : base(viewContext)
        {
            this.Type(ButtonTypeEnum.button);
        }
                                             
        internal string _title = "";
        internal ColorPaletteEnum _color = ColorPaletteEnum.@default;
        internal string _iconHtml = "";
        internal bool _hide = false;

        public ButtonCmdBase Command { set; get; }

        public string GetText => _title;

        public ColorPaletteEnum GetColor => _color;
        
        
    }


    public interface ICommandElement
    {
        ButtonCmdBase Command { set; get; }
    }


    public abstract class ButtonCmdBase 
    {
        public virtual void RenderToButton(ButtonConfigBase btn)
        {
            RenderToElement(btn.Attributes);
        }

        public abstract void RenderToElement(TagAttrbute attr);

        public virtual string RenderToString()
        {
            var attr=new TagAttrbute();

            RenderToElement(attr);

            return attr.ToStringEx();
        }
    }

    /// <summary>
    /// 弹出一个指定Url窗口
    /// </summary>
    public class ButtonCmd_ShowModal: ButtonCmdBase
    {
        private string _url = "";
        private string _onsuccess = "";
        private string _onClose = "";
        private bool _shadeClose = true;

        public ButtonCmd_ShowModal SetUrl(string url)
        {
            _url = url;

            return this;
        }

        public ButtonCmd_ShowModal SetOnSuccessCallback(string callback)
        {
            _onsuccess = callback;

            return this;
        }

        public ButtonCmd_ShowModal SetOnCloseModalCallback(string callback)
        {
            _onClose = callback;

            return this;
        }

        public ButtonCmd_ShowModal SetDisabledShadeClose(bool disabledShadeClose = true)
        {
            _shadeClose = !disabledShadeClose;
            return this;
        }
        
        public override void RenderToElement(TagAttrbute attr)
        {
            var script=$"WebUIJS.ModalByUrl('{_url}',null,{(string.IsNullOrWhiteSpace(_onsuccess) ? "null" : "'" + _onsuccess + "'")},{(string.IsNullOrWhiteSpace(_onClose)?"null":"'" + _onClose + "'")},'GET',false,{_shadeClose.ToString().ToLower()})"; //,{{shadeClose:{_shadeClose.ToString().ToLower()}}}

            attr.Attributes.Add("onclick", script);
        }
    }

    public class ButtonCmd_Goto : ButtonCmdBase
    {
        private string _url = "";
        private LinkTargetType _linkTarget = LinkTargetType.Self;
        private bool _isOpenToBrowser = false;

        public ButtonCmd_Goto SetUrl(string url)
        {
            _url = url;

            return this;
        }

        public ButtonCmd_Goto SetTarget(LinkTargetType target)
        {
            _linkTarget = target;

            return this;
        }

        public string Url => _url;

        public LinkTargetType TaragetType => _linkTarget;

        /// <summary>
        /// 当使用iframe模式的时候,该属性用于设置打开连接时,直接打开新的浏览器页面,
        /// </summary>
        /// <param name="isOpenToBrowser"></param>
        /// <returns></returns>
        public ButtonCmd_Goto SetOpenToBrowser(bool isOpenToBrowser = false)
        {
            _isOpenToBrowser = isOpenToBrowser;

            return this;
        }


        public override void RenderToElement(TagAttrbute attr)
        {
            var target = Utility.LinkTargetToStr(_linkTarget);

            var btnType = attr.GetValue("type", "button");

            if (btnType=="link")
            {
                attr.SetOrReplaceAttr("href", _url);
                attr.SetOrReplaceAttr("target", target);
                attr.SetOrReplaceAttr("webui-ignore", "webui-ignore");
            }
            else
            {
                var script = $"WebUIJS.GoTo('{_url}',this,'{target}',{(!_isOpenToBrowser).ToStringEx().ToLower()})";

                attr.SetOrReplaceAttr("onclick", script);
            }
            
        }
    }

    public class ButtonCmd_ClientClick : ButtonCmdBase
    {
        private string _script = "";
   
        public ButtonCmd_ClientClick SetOnClickScript(string script)
        {
            _script = script;

            return this;
        }

        public string Script => _script;
        
        public override void RenderToElement(TagAttrbute attr)
        {
            attr.SetOrReplaceAttr("onclick", _script);
        }
    }

    /// <summary>
    /// 异步执行一个功能命令
    /// </summary>
    public class ButtonCmd_ExecuteCmd : ButtonCmdBase
    {
        private JObject _args = null;
        private string _url = "";
        private string _cmdName = "";
        private string _tips = "";
        private bool _isAutoReresh = false;
        private string _afterCallabck = "";
        private bool _isAutoRefreshWholePage = false;

        public ButtonCmd_ExecuteCmd AutoRefreshPage(bool isAutoRefresh=true)
        {
            _isAutoReresh = isAutoRefresh;

            return this;
        }

        public ButtonCmd_ExecuteCmd AutoRefreshWholePage(bool isAutoRefresh = true)
        {
            _isAutoRefreshWholePage = isAutoRefresh;

            return this;
        }

        public ButtonCmd_ExecuteCmd SetTips(string tips)
        {
            _tips = tips;

            return this;
        }

        public ButtonCmd_ExecuteCmd SetArgs(JObject args)
        {
            _args = args;

            return this;
        }

        public ButtonCmd_ExecuteCmd SetArgs(object args)
        {
            _args = JObject.FromObject(args);

            return this;
        }

        public ButtonCmd_ExecuteCmd SetCmdUrl(string url)
        {
            _url = url;

            return this;
        }

        public ButtonCmd_ExecuteCmd SetMethodName(string cmdName)
        {
            _cmdName = cmdName;

            return this;
        }

        public ButtonCmd_ExecuteCmd SetOnSuccessCallback(string callback)
        {
            _afterCallabck = callback;

            return this;
        }

        public override void RenderToElement(TagAttrbute attr)
        {
            var onclick = "WebUIJS.AjaxToMethod(this);";

            attr.Data("data-args", WebUtility.HtmlEncode(_args.ToString(Formatting.None)));
            attr.Data("data-cmd", _cmdName);
            attr.Data("data-tips", _tips);
            attr.Data("data-url", _url);
            
            attr.Data("data-autorefresh", _isAutoReresh.ToStringEx());
            attr.Data("data-autorefreshwholepage", _isAutoRefreshWholePage.ToStringEx());

            attr.Data("data-aftersuccesscall", _afterCallabck.ToStringEx());
            attr.SetOrReplaceAttr("onclick", onclick);
        }
    }

    /// <summary>
    /// 弹出一个取数窗口
    /// </summary>
    public class ButtonCmd_ShowDataPicker : ButtonCmdBase
    {
        private string _url="";
        private string _selectedCallback = "";
        private string _showCallback = "";
        private JObject _fillConfig = null;
        private bool _storeInCache = false;
        private string _fillToTextFieldName = "";
        private string _fillToValueFieldName = "";
        private string _selectedAreaTableOrderbyKey = "";
        private int _selectedAreaTableOrderbyType = 0;

        public ButtonCmd_ShowDataPicker SetUrl(string url)
        {
            _url = url;
            return this;
        }

        public ButtonCmd_ShowDataPicker OnSelectedCallback(string callback)
        {
            _selectedCallback = callback;

            return this;
        }

        public ButtonCmd_ShowDataPicker OnShowCallback(string callback)
        {
            _showCallback = callback;

            return this;
        }

        public ButtonCmd_ShowDataPicker StoreInCache(bool isStoreInCache)
        {
            _storeInCache = isStoreInCache;
            return this;
        }

        public ButtonCmd_ShowDataPicker FillConfig(JObject fillConfig)
        {
            _fillConfig = fillConfig;

            return this;
        }


        /// <summary>
        /// 排序字段
        /// </summary>
        /// <param name="thCssName"></param>
        /// <param name="isAsc">是否为正序</param>
        /// <returns></returns>
        public ButtonCmd_ShowDataPicker SelectedAreaTableOrderbyKey(string thCssName, bool isAsc = true)
        {
            _selectedAreaTableOrderbyKey = thCssName;
            _selectedAreaTableOrderbyType = isAsc ? 0 : -1;

            return this;
        }

        /// <summary>
        /// 填充到文本框的字段的名称
        /// </summary>
        /// <param name="jsonFieldName">返回的数据中的字段名</param>
        /// <returns></returns>
        public ButtonCmd_ShowDataPicker FillToTitle(string jsonFieldName)
        {
            _fillToTextFieldName = jsonFieldName;

            return this;
        }

        /// <summary>
        /// 填充到文本框的字段的名称
        /// </summary>
        /// <param name="jsonFieldName">返回的数据中的字段名</param>
        /// <returns></returns>
        public ButtonCmd_ShowDataPicker FillToValue(string jsonFieldName)
        {
            _fillToValueFieldName = jsonFieldName;

            return this;
        }

        public override void RenderToElement(TagAttrbute attr)
        {
            if (_fillConfig!=null)
            {
                attr.Data("data-fillconfig", HttpUtility.HtmlEncode(_fillConfig.ToString(Formatting.None)));

                _selectedCallback = $"__dataPickerToConfig";
            }
            
            attr.Data("data-showdatapicker", _url);
            attr.Data("data-selectedcallback", _selectedCallback);

            attr.Data("data-showcallback", _showCallback);
            attr.Data("data-filltotitle", _fillToTextFieldName);
            attr.Data("data-filltovalue", _fillToValueFieldName);
            attr.Data("data-orderby", _selectedAreaTableOrderbyKey.ToStringEx());
            attr.Data("data-orderbytype", _selectedAreaTableOrderbyType.ToStringEx());

            attr.Data("data-option", HttpUtility.HtmlEncode(new JObject()
                                                       {
                                                           {"StoreInCache", _storeInCache}
                                                       }.ToStringEx(Formatting.None)));

            attr.Class("datapickerbtn");

            //attr.SetOrReplaceAttr("onclick", $"WebUIJS.ShowDataPicker('{_url}','{_selectedCallback}','{_showCallback}',{{StoreInCache:{_storeInCache.ToString().ToLower()}}},$(this))");

        }
    }
    
}
